<?
    /* -*- Mode: PHP5; tab-width: 4; indent-tabs-mode: nil; basic-offset: 4 -*- */


    /*********************************************************
    *            --== InArch ==--
    *
    * INA Client Core, this in every solution's heart and soul. The main
    * purpose of this file is to cast all the objects neccessary
    * for some part of a solution. It is also the URI parser which
    * figures out what part of the solution the user has requested.
    * 
    * It is vital that the init.inc.php file is called at the
    * beginning of this file, as it will grant all the neccessary
    * resources for the application in form of a database layer
    * and a template parser.
    * 
    * clientCore.inc.php is a subfile, meaning that it will be called by
    * any solution inside client part of the application. Thus it
    * is neccessary that the solution provides clientCore.inc.php with 
    * two constants: INA_ROOT and ROOT both resembling path to
    * the INA core files and the solution's root respectively.
    *
    * @author Kulikov Alexey <a.kulikov@gmail.com>
    * @version n/a
    * @since 02.05.2005
    * @copyright essentialmind.com 2005
    *
    *********************************************************/
   
    //get hold of the control framework
    //it casts $db, $smarty and $_CONFIG
    require_once INA_ROOT.'init.inc.php';
    
    //create Client Log Writer (global scope)
    $GLOBALS['myLog'] = new logDB($db,'client',$_CONFIG['print_errors']);
    
    
    ###### -- Bot Image Request? -- ################
    #
    /*
        Please note, that the creation of a bot image
        automatically terminates further execution
        of the script
    */
    if(isset($_GET['returnimage'])){
        $myBot = new botImage();
        $myBot->getImage($_SESSION['botNumber']);   
    }
    #
    ###### -- End Bot Image Request -- #############
    
    
    ###### -- Ajax Voodoo? -- ######################
    #
    if(isset($_GET['ajax']) and $_REQUEST['action']){
        try{
            $myAjax = ajaxFactory::cast($_REQUEST['action'],$db,$smarty,$myLog);
            $myAjax->process();
        }catch(exception $e){   //something went terribly wrong
            $myLog->verbose = true;
            $myLog->recordError($e->getMessage());
        }
        exit;
    }
    #
    ###### -- End Ajax Voodoo -- ###################
    
    
    ###### -- Cron Job Request? -- #################
    #
    /*
        Please note, that the creation of a cron job
        automatically terminates further execution
        of the script
    */
    if((isset($argv) and isset($argv[1])) or isset($_GET['cron'])){
        try{
            
            $myCron = cronFactory::cast(($argv[1]?$argv[1]:$_GET['cron']),$db,$smarty,$myLog);
            $myCron->process();
            
        }catch(exception $e){   //something went terribly wrong
            $myLog->verbose = true;
            $myLog->recordError($e->getMessage());
        }
        exit;
    }
    #
    ###### -- End Cron Job Request -- ##############


    ###### -- End user session? -- #################
    #
    if(isset($_GET['logout'])){
        //clean session
        session_destroy();
        
        //clean autologin cookies
        setcookie('cp_autologin',null,time(),'/');
        
        //redirect to root
        header("Location: ".$GLOBALS['_CONFIG']['server_root']);
        exit;   
    }
    #
    ###### -- /End user session? -- ################
    
    
    
    
    
    
    
         ##########################
         #                        #
    ###### -- Init Client Core -- ##################
    #
    //init the breadcrumbs data holder
    $breadCrumbs = new breadcrumbs($db,$_CONFIG['server_root']);
    
    // mark the root of the site with a breadcrumb
    $breadCrumbs->push('Home',null);
    #
    ###### -- End Init Client Core -- ##############
         #
         #
    ###### -- Client Node Registry -- ##############
    #
    //first we need to figure out the node type
    //this is done by recursively walking the tree
    //or checking the path cache (latter may yield
    //faster results.
    $myNavigator        = new clientTreeNavigator($db,$myLog);
    $GLOBALS['cacheID'] = $myNavigator->getCacheID();

    //rss?
    if($_GET['out'] == 'rss'){
        $cacheID['full'] = $cacheID['full'].'|rss';
    }
    
    /*
      It is a big pity the following two line of code had to
      be moved outside of the if(cache) statement, but this
      is the only way to check, whether the page needs
      password authorization or not alongside with 
      caching password protected content!
    */
    //the nodeData will have a codeset pointer and an
    //object ID, which from we will be able to cast
    //our clientNode with content
    $nodeData    = $myNavigator->getNodeData();
    
    //free up some RAM =)
    unset($myNavigator);
    
    if($_SESSION['admin']){
        $smarty->caching = false;
    }
    
    //if($_GET['debug']){print_r($nodeData);}    
    //first thing to do, is check whether the requested page
    //is present in the local static cache
    if(!$smarty->is_cached('index.html',$cacheID['full'])){
   
        //let's try to get some content
        try{
            //see if the address resolved locally
            if(!$nodeData){ //no!!!
                //thus throw an exception, which will be cast into a 404 page
                throw new exception('The requested page was not found!',404);
            }
            
            //now, this is an exception to the whole handling routine
            //hail to the mighty search request!
            if(isset($_GET['search'])){
                /*
                    It is worth to note, that this could be a potential
                    weakness of the site in case one would want to stess
                    test the performance of the site with the aid of a
                    DDoS attack. Thus the search result pages will be
                    ALWAYS cached for 10 minutes.
                */
                $nodeData['codeset'] = 'search';
            }
    
            //ok, $nodeData resolved, thus cast the necessary controller
            $controller = clientFactory::cast($nodeData['codeset'],$db,$smarty,$myLog,$breadCrumbs);
            $controller->setReferences($nodeData['objectid'], $nodeData['nodeid'], $nodeData['pageref']);
                        
            //create breadcumb array
            /*
                plase note, that this procedure costs two database queries. In case
                performace is an issue, then use the ZEND profiler to estimate the
                overall cost of this procedure and cut it out in case needed
            */
            $breadCrumbs->calculate($nodeData['nodeid'], $nodeData['pageref'], $nodeData['codeset']);
        
        // no joy, thus cast a 404
        }catch(exception $e){
            //create a 404 breadcrumb
            $breadCrumbs->push('404, Page Not Found',null);
            
            /*
                please note, that in case a node module could not be
                loaded, then a 404 page is generated in order to 
                avoid feeding errors to the client. The Error message can be
                always read in the corresponding ErrorLog, wherever it is
                directed to.
            */
    
            //record error message
            $myLog->recordError($e->getMessage(),$e->getCode(),true);
            
            //cast a 404 page controller
            $controller = clientFactory::cast('404',$db,$smarty,$myLog,$breadCrumbs);
        }
        
        #
        ###### -- End Client Node Registry -- ############
             #
             #
        ###### -- Actual Functionality -- ################
        #
        //see if we can show what we are asked to show
        try{
            $controller->display('index.html',$cacheID['full']);

        //what a pity, no joy!
        }catch(exception $e){
        
            //get hold of the error message
            $myLog->recordError($e->getMessage(),$e->getCode());
            
            //display an internal server error page
            //$smarty->display("500.html");
        }

    
    //get the page from cache, as it is there, yeah!
    }else{
       
        $smarty->display('index.html',$cacheID['full']);
    }
    #
    ###### -- This Code is Severely Beautiful -- #########
